using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;

namespace DynamicConfigurationManager.ConfigMapAttributes
{
    /// <summary>
    /// this class is very unreliable
    /// release builds will sometimes optimize away entire methods, so the call stack would be different
    /// see: http://stackoverflow.com/a/15368508/57883
    /// </summary>
    internal class CallingTypeFullnameRegEx : IConfigMapAttribute
    {
        public bool Execute( string configMapAttribute )
        {
            var re = new Regex( configMapAttribute, RegexOptions.IgnoreCase );

            foreach( var t in GetCallingTypesFullNames() )
            {
                LogHelper.Append( "CallingTypeRegEx: matching to {0}", t );
                if( re.IsMatch( t ) )
                {
                    return true;
                }
            }
            return false;
        }

        public static IEnumerable<string> GetCallingTypesFullNames()
        {
            var stackTrace = new StackTrace();
            var frames = stackTrace.GetFrames();
            return frames?.Select( f => f.GetMethod().DeclaringType ).Distinct().Select( t => t.FullName );
        }
    }
}